<template>
  <div>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
      :offset="30"
      @load="onLoad"
    >
      <div v-for="answerList in newAnswerList" :key="answerList.date">
        <!-- 时间分割线 -->
        <div class="list-head" v-if="today !== answerList.date">
          <span class="list-head-time">{{
            getMonthAndDay(answerList.date)
          }}</span>
          <hr />
        </div>
        <!-- 回答简介 -->
        <van-cell v-for="answer in answerList.stories" :key="answer.id" @click="toDetail(answer.id)">
          <template #title> {{ answer.title }} </template>
          <template #value>
            <van-image width="75" height="75" :src="answer.images[0]" />
          </template>
          <template #label> {{ answer.hint }} </template>
        </van-cell>
      </div>
    </van-list>
  </div>
</template>

<script>
import { reactive, toRefs, inject } from 'vue'
import { useRouter } from 'vue-router'
import { getTimeFormat, getMonthAndDay } from '@/utils/time'
export default {
  name: 'AnswerList',
  props: {
    newAnswerList: {
      type: Array,
    },
  },
  setup() {
    const $router = useRouter()

    let state = reactive({
      loading: false,
      finished: false,
      today: '',
    })
    // 获取当前的时间
    state.today = getTimeFormat()

    let num = 0
    // 加载更多的回答列表
    const getMoreAnswer = inject('getMoreAnswer')

    // 下滑时获取更多的回答
    const onLoad = () => {
      // 开始加载
      state.loading = true
      getMoreAnswer(num)
      // 结束加载
      state.loading = false
      // 往后的多少天
      num++
    }

    // 跳转到回答详情页面
    const toDetail = (id) => {
      $router.push({
        name: 'detail',
        params: {id}
      })
    }

    return {
      ...toRefs(state),
      getMonthAndDay,
      onLoad,
      toDetail
    }
  },
}
</script>

<style lang='less' scoped>
/deep/ .van-cell__title {
  flex: 4;
  font-size: 14px;
  font-weight: 700;
}
/deep/ .van-cell__label {
  margin-top: 8px;
  font-weight: normal;
}
.list-head {
  display: flex;
  justify-content: center;
  padding: 10px 0 10px 15px;
  &-time {
    margin-top: 20px;
    padding-right: 10px;
    font-size: 14px;
  }
  hr {
    flex: 1;
    color: #eee;
  }
}
</style>